//
//  SLEmoticonToolBar.swift
//  Emotion
//
//  Created by lirenqiang on 16/6/1.
//  Copyright © 2016年 lirenqiang. All rights reserved.
//

import UIKit

let baseTag = 1000

class SLEmoticonToolBar: UIStackView {

    /**
     *  用来记录选中的按钮
     */
    var selectedBtn: UIButton?
    
    var selectedIndex: ((index: Int)->())?
    
    
    
    init() {
        super.init(frame: CGRectZero)
        
        //设置轴
        axis = .Horizontal
        
        //设置分布方式
        distribution = .FillEqually
        
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    //MARK: - 添加按钮
    private func setupUI() {
        
//        addChildButtons("默认", backImageName: "compose_emotion_table_left", tag: 0)
//        addChildButtons("Emoji", backImageName: "compose_emotion_table_mid", tag: 1)
//        addChildButtons("浪小花", backImageName: "compose_emotion_table_right", tag: 2)
        
        let packages = SLEmoticonManager().packages
        
        for i in 0..<packages.count {
            
            let package = packages[i]
            
            var backImageName = "compose_emotion_table_mid"
            
            if i == 0 {
                backImageName = "compose_emotion_table_left"
            } else if i == packages.count - 1 {
                backImageName = "compose_emotion_table_right"
            }
            
            addChildButtons(package.title!, backImageName: backImageName, tag: i)
            
            
        }
        
    }
    
    private func addChildButtons(title: String, backImageName: String, tag: Int) {
        
        let btn = UIButton()
        
        btn.tag = tag + baseTag
        
        btn.setTitle(title, forState: .Normal)
        btn.setTitleColor(UIColor.darkGrayColor(), forState: .Selected)
        btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        
        btn.setBackgroundImage(UIImage(named: backImageName+"_normal"), forState: .Normal)
        btn.setBackgroundImage(UIImage(named: backImageName+"_selected"), forState: .Selected)
        
        btn.addTarget(self, action: #selector(SLEmoticonToolBar.btnAction(_:)), forControlEvents: .TouchUpInside)
        
        if tag == 0 {
            btn.selected = true
            selectedBtn = btn
        }
        
        addArrangedSubview(btn)
    }
    
    @objc private func btnAction(btn: UIButton) {
        
        selectedBtn?.selected = false
        
        btn.selected = true
        
        selectedBtn = btn
        
        selectedIndex?(index: btn.tag - baseTag)
        
    }
    
    func setSelectedButton(section: Int) {
        
        selectedBtn?.selected = false
        
        let btn = self.viewWithTag(section+baseTag) as! UIButton
        
        btn.selected = true
        
        selectedBtn = btn
        
        
    }
    
    
}




































